// pages/music/music.js
function parseLyric(lrc) {
  var lyrics = lrc.split("\n");
  var lrcObj = {};
  for (var i = 0; i < lyrics.length; i++) {
    var lyric = decodeURIComponent(lyrics[i]);
    var timeReg = /\[\d*:\d*((\.|\:)\d*)*\]/g;
    var timeRegExpArr = lyric.match(timeReg);
    if (!timeRegExpArr) continue;
    var clause = lyric.replace(timeReg, '');
    for (var k = 0, h = timeRegExpArr.length; k < h; k++) {
      var t = timeRegExpArr[k];
      var min = Number(String(t.match(/\[\d*/i)).slice(1)),
        sec = Number(String(t.match(/\:\d*/i)).slice(1));
      var time = min * 60 + sec;
      lrcObj[time] = clause;
    }
  }
  return lrcObj;
}

Page({  
  loadMore:function(){
    var that = this;
    wx.showLoading({
      title:'数据加载中'
    })    
    var newOffset = (that.data.page - 1)*that.data.size;
    wx.request({
      url: 'http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.billboard.billList&type=1',
      header: {
        'content-type': 'application/json' // 默认值
      },
      data:{
        //type: that.data.page,
        size: that.data.size,
        offset: newOffset
      },
      success: (res) => {
        //console.log(res.data.song_list)
        //var idList = [];
        //console.log(res.data.song_list.length);
        for(var i = 0;i<res.data.song_list.length;i++){
          that.data.musicList.push(res.data.song_list[i])          
        }
        that.setData({
          musicList: that.data.musicList          
        });
        setTimeout(function(){
          wx.hideLoading()
        },500);
        that.data.page++;        
      }
    })
  }, 
  onReady: function (e) {
    // 使用 wx.createAudioContext 获取 audio 上下文 context
    this.audioCtx = wx.createAudioContext('myAudio');
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          scrollHeight: res.windowHeight-135
        })        
      }
    })
    wx.request({
      url: 'http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.billboard.billList&type=1', 
      header: {
        'content-type': 'application/json' // 默认值
      },
      data:{
        //type:that.data.page,
        size:that.data.size,
        offset: that.data.offset
      },
      success:(res)=> {        
        //console.log(res)
        that.setData({
          musicList: res.data.song_list          
        })
      }
    })
  },  
  data: {    
    size:5,
    offset:0,
    page:2,
    musicList:[],    
    scrollHeight:0, 
    musicPercent:0,
    playMusicId:0, 
    //musicPercentChange:0,
    musicIsChange:false,
    musicLrc:{},
    musicText:"这里是歌词",
    musicTime:0,  
    poster: 'http://y.gtimg.cn/music/photo_new/T002R300x300M000003rsKF44GyaSk.jpg?max_age=2592000',
    name: '此时此刻',
    author: '许巍',
    src: 'http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E06DCBDC9AB7C49FD713D632D313AC4858BACB8DDD29067D3C601481D36E62053BF8DFEAF74C0A5CCFADD6471160CAF3E6A&fromtag=46',
  },
  handleMusic:function(e){
    //console.log(e.currentTarget.dataset.idx)
    var that = this;
    var index = e.currentTarget.dataset.idx;    
    //console.log(that.data.musicList[index].song_id)    
    wx.request({
      url: 'http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.song.play',
      header: {
        'content-type': 'application/json' // 默认值
      },
      data: {
        songid: that.data.musicList[index].song_id
      },
      success: (res) => {
        
        that.setData({
          poster: that.data.musicList[index].pic_small,
          name: that.data.musicList[index].album_title,
          author: that.data.musicList[index].author,
          playMusicId:index
          //src: res.data.bitrate.show_link
        });
        that.audioCtx.setSrc(res.data.bitrate.show_link)
        that.audioCtx.play();
        /*
        console.log(res.data.songinfo.lrclink);

        wx.request({
          url: res.data.songinfo.lrclink ,
          header: {
            'content-type': 'application/json' // 默认值
          },
          success:(res)=>{
            this.setData({
              musicLrc: parseLyric(res.data)
            })
          }
        })
        */
      }
    })    
  },
  timeupdate:function(e){    
    //console.log(e); 
    if (this.data.musicIsChange) {
      this.audioCtx.seek(this.data.musicPercent / 100 * e.detail.duration);    
      this.setData({        
        musicIsChange: false,
        musicTime: Math.ceil(this.data.musicPercent / 100 * e.detail.duration)
      })
    }else{
      var percent = Math.ceil(e.detail.currentTime / e.detail.duration * 100);
      this.setData({
        musicPercent: percent,
        musicTime: Math.ceil(e.detail.currentTime)
      })
    }    
    this.autoPlay();
    this.getSong();
  },
  sliderChange:function(e){    
    //console.log(e.detail.value);
    this.setData({      
      musicPercent: e.detail.value,
      musicIsChange:true
    })    
  },
  autoPlay:function(){
    var that = this;
    if (that.data.musicPercent == 100) {
      var index = that.data.playMusicId + 1;
      that.setData({
        playMusicId: index
      })
      wx.request({
        url: 'http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.song.play',
        header: {
          'content-type': 'application/json' // 默认值
        },
        data: {
          songid: that.data.musicList[index].song_id
        },
        success: (res) => {
          
          that.setData({
            poster: that.data.musicList[index].pic_small,
            name: that.data.musicList[index].album_title,
            author: that.data.musicList[index].author,
            playMusicId: index
            //src: res.data.bitrate.show_link
          });
          that.audioCtx.setSrc(res.data.bitrate.show_link)
          that.audioCtx.play();
        }
      })
    } 
  },
  getSong:function(){
    //console.log(this.data.musicList[this.data.playMusicId])
    wx.request({
      url: this.data.musicList[this.data.playMusicId].lrclink,
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: (res) => {
        this.setData({
          musicLrc: parseLyric(res.data)                            
        })
        this.setData({
          musicText: this.data.musicLrc[this.data.musicTime]  
        })
//console.log(this.data.musicLrc)
//console.log(this.data.musicTime);

      }
    })
  }
})

